package com.adk.backend.controller;

import com.adk.backend.annotation.RequiresPermission;
import com.adk.backend.common.Result;
import com.adk.backend.entity.LxServiceList;
import com.adk.backend.service.ServiceListService;
import com.adk.backend.service.impl.ServiceListServiceImpl;
import com.adk.backend.util.FileUploadUtil;
import com.adk.backend.util.JwtUtil;
import com.adk.backend.util.LogUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 服务管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/service")
public class ServiceListController {
    
    @Autowired
    private ServiceListService serviceListService;
    
    @Autowired
    private ServiceListServiceImpl serviceListServiceImpl;
    
    @Autowired
    private FileUploadUtil fileUploadUtil;
    
    @Autowired
    private LogUtil logUtil;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    /**
     * 查询服务列表
     */
    @RequiresPermission("list")
    @GetMapping("/list")
    public Result<List<Map<String, Object>>> getServiceList(
            @RequestParam(required = false) Long cId,
            @RequestParam(required = false) Integer country,
            @RequestParam(required = false) Integer typeId,
            @RequestParam(required = false) Integer status,
            @RequestHeader(value = "Authorization", required = false) String token) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("cId", cId);
            params.put("country", country);
            params.put("typeId", typeId);
            params.put("status", status);
            
            List<Map<String, Object>> list = serviceListService.getServiceList(params);
            return Result.success(list);
        } catch (Exception e) {
            log.error("查询服务列表失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID查询服务详情
     */
    @RequiresPermission("view")
    @GetMapping("/detail")
    public Result<Map<String, Object>> getServiceDetail(@RequestParam Long id) {
        try {
            Map<String, Object> detail = serviceListService.getServiceDetailById(id);
            if (detail == null) {
                return Result.error("服务不存在");
            }
            return Result.success(detail);
        } catch (Exception e) {
            log.error("查询服务详情失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 保存服务（新增或更新）
     */
    @RequiresPermission("edit")
    @PostMapping("/save")
    public Result<Boolean> saveService(
            @RequestParam(required = false) Long id,
            @RequestParam Long cId,
            @RequestParam Integer typeId,
            @RequestParam(required = false) Integer country,
            @RequestParam(required = false) String orderNo,
            @RequestParam(required = false) String contents,
            @RequestParam(required = false) String ctnNo,
            @RequestParam(required = false) MultipartFile[] attr,
            @RequestHeader(value = "Authorization", required = false) String token,
            HttpServletRequest request) {
        try {
            Integer userId = getCurrentUserId(token);
            
            LxServiceList service = new LxServiceList();
            if (id != null && id > 0) {
                service.setId(id);
                // 获取原有服务信息
                Map<String, Object> existingServiceMap = serviceListService.getServiceDetailById(id);
                
                // 如果上传了新文件，删除旧文件
                if (attr != null && attr.length > 0 && existingServiceMap != null && existingServiceMap.get("attr") != null) {
                    String attrStr = existingServiceMap.get("attr").toString();
                    if (attrStr != null && !attrStr.isEmpty()) {
                        String[] oldFiles = attrStr.split(",");
                        for (String file : oldFiles) {
                            if (file != null && !file.trim().isEmpty()) {
                                fileUploadUtil.deleteLocalFile("./uploads/service/u/" + file.trim());
                            }
                        }
                    }
                }
            } else {
                service.setAddUid(userId);
                service.setAddTime((int) (System.currentTimeMillis() / 1000));
                service.setStatus(1); // 默认待处理
            }
            
            service.setCId(cId);
            service.setTypeId(typeId);
            service.setCountry(country);
            service.setOrderNo(orderNo);
            service.setContents(contents);
            service.setCtnNo(ctnNo);
            
            // 处理文件上传
            if (attr != null && attr.length > 0) {
                String uploadedFiles = serviceListServiceImpl.uploadServiceFiles(attr, userId);
                if (uploadedFiles != null) {
                    service.setAttr(uploadedFiles);
                }
            }
            
            // 如果是更新，设置更新用户ID和更新时间（与PHP逻辑一致）
            if (id != null && id > 0) {
                service.setUpdateUid(userId);
                service.setUpdateTime((int) (System.currentTimeMillis() / 1000));
            }
            
            boolean success = serviceListService.saveService(service);
            if (success) {
                String action = id != null && id > 0 ? "修改服务" : "添加服务";
                // 使用简化的logAction方法
                logUtil.logAction(getCurrentUserIdLong(token), "service_list", service.getId(), action);
                String message = id != null && id > 0 ? "修改成功" : "添加成功";
                return Result.success(message, true);
            } else {
                return Result.error("操作失败");
            }
        } catch (Exception e) {
            log.error("保存服务失败", e);
            return Result.error("保存失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除服务
     */
    @RequiresPermission("del")
    @PostMapping("/del")
    public Result<Boolean> deleteService(
            @RequestParam Long id,
            @RequestHeader(value = "Authorization", required = false) String token,
            HttpServletRequest request) {
        try {
            boolean success = serviceListService.deleteService(id);
            if (success) {
                logUtil.logAction(getCurrentUserIdLong(token), "service_list", id, "删除服务");
                return Result.success("删掉了", true);
            } else {
                return Result.error("Data Error");
            }
        } catch (Exception e) {
            log.error("删除服务失败", e);
            return Result.error("删除失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新服务状态
     */
    @RequiresPermission("edit")
    @PostMapping("/update-status")
    public Result<Boolean> updateServiceStatus(
            @RequestParam Long id,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String bookingDate,
            @RequestParam(required = false) String rRemarks,
            @RequestParam(required = false) MultipartFile[] rAttr,
            @RequestHeader(value = "Authorization", required = false) String token,
            HttpServletRequest request) {
        try {
            Integer userId = getCurrentUserId(token);
            
            String rAttrStr = null;
            if (rAttr != null && rAttr.length > 0) {
                rAttrStr = serviceListServiceImpl.uploadServiceRAttrFiles(rAttr, userId);
            }
            
            boolean success = serviceListService.updateServiceStatus(id, status, bookingDate, rRemarks, rAttrStr, userId);
            if (success) {
                logUtil.logAction(getCurrentUserIdLong(token), "service_list", id, "更新服务状态");
                return Result.success("操作成功", true);
            } else {
                return Result.error("操作失败");
            }
        } catch (Exception e) {
            log.error("更新服务状态失败", e);
            return Result.error("更新失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除附件
     */
    @RequiresPermission("edit")
    @PostMapping("/del-attr")
    public Result<Boolean> deleteAttachment(
            @RequestParam Long id,
            @RequestParam String fileName,
            @RequestHeader(value = "Authorization", required = false) String token,
            HttpServletRequest request) {
        try {
            Integer userId = getCurrentUserId(token);
            boolean success = serviceListService.deleteAttachment(id, fileName, userId);
            if (success) {
                logUtil.logAction(getCurrentUserIdLong(token), "service_list", id, "删除附件" + fileName);
                return Result.success("删掉了", true);
            } else {
                return Result.error("数据错误");
            }
        } catch (Exception e) {
            log.error("删除附件失败", e);
            return Result.error("删除失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取账单编辑信息
     */
    @RequiresPermission("view")
    @GetMapping("/billing-info")
    public Result<Map<String, Object>> getBillingInfo(
            @RequestParam Long serviceId) {
        try {
            Map<String, Object> result = serviceListService.getBillingInfo(serviceId);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取账单信息失败", e);
            return Result.error("获取账单信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 保存账单（创建或更新）
     */
    @RequiresPermission("edit")
    @PostMapping("/save-billing")
    public Result<Boolean> saveBilling(
            @RequestParam Long serviceId,
            @RequestBody Map<String, Object> billingData,
            @RequestHeader(value = "Authorization", required = false) String token,
            HttpServletRequest request) {
        try {
            Integer userId = getCurrentUserId(token);
            // 先获取账单信息，判断是创建还是更新
            Map<String, Object> billingInfoBefore = serviceListService.getBillingInfo(serviceId);
            boolean isUpdate = (billingInfoBefore != null && billingInfoBefore.get("billingId") != null && 
                Long.parseLong(billingInfoBefore.get("billingId").toString()) > 0);
            
            boolean success = serviceListService.saveBilling(serviceId, billingData, userId);
            if (success) {
                String action = isUpdate ? "更新账单" : "创建账单";
                logUtil.logAction(getCurrentUserIdLong(token), "service_list", serviceId, action);
                return Result.success("Success.", true);
            } else {
                return Result.error("Data Error");
            }
        } catch (Exception e) {
            log.error("保存账单失败", e);
            return Result.error("保存账单失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除账单明细项
     */
    @RequiresPermission("edit")
    @PostMapping("/delete-billing-detail")
    public Result<Boolean> deleteBillingDetailItem(
            @RequestParam Long detailId,
            @RequestHeader(value = "Authorization", required = false) String token,
            HttpServletRequest request) {
        try {
            boolean success = serviceListService.deleteBillingDetailItem(detailId);
            if (success) {
                logUtil.logAction(getCurrentUserIdLong(token), "service_list", detailId, "删除账单明细项");
                return Result.success("删除收费项成功,请刷新页面以获取最新数据", true);
            } else {
                return Result.error("没有找到这个项，请刷新页面重试");
            }
        } catch (Exception e) {
            log.error("删除账单明细项失败", e);
            return Result.error("删除失败：" + e.getMessage());
        }
    }
    
    /**
     * 文件预览/下载
     */
    @RequiresPermission("view")
    @GetMapping("/file")
    public ResponseEntity<Resource> getFile(
            @RequestParam String filePath,
            @RequestParam(required = false, defaultValue = "download") String action) {
        try {
            // 防止路径遍历攻击
            if (filePath.contains("..") || filePath.contains("/") || filePath.contains("\\")) {
                // 只允许文件名
                filePath = filePath.substring(filePath.lastIndexOf("/") + 1);
            }
            
            String cleanPath = filePath.startsWith("./uploads/service/u/") ? 
                filePath.substring(2) : 
                (filePath.startsWith("uploads/service/u/") ? filePath : "uploads/service/u/" + filePath);
            
            File file = new File(cleanPath);
            if (!file.exists() || !file.isFile()) {
                return ResponseEntity.notFound().build();
            }
            
            Resource resource = new FileSystemResource(file);
            
            HttpHeaders headers = new HttpHeaders();
            if ("preview".equals(action)) {
                // 预览模式
                String contentType = getContentType(file.getName());
                headers.setContentType(MediaType.parseMediaType(contentType));
                headers.setContentDispositionFormData("inline", file.getName());
            } else {
                // 下载模式
                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                headers.setContentDispositionFormData("attachment", file.getName());
            }
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(resource);
        } catch (Exception e) {
            log.error("获取文件失败", e);
            return ResponseEntity.notFound().build();
        }
    }
    
    private String getContentType(String fileName) {
        String extension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        switch (extension) {
            case "jpg":
            case "jpeg":
                return "image/jpeg";
            case "png":
                return "image/png";
            case "pdf":
                return "application/pdf";
            case "xls":
                return "application/vnd.ms-excel";
            case "xlsx":
                return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            default:
                return "application/octet-stream";
        }
    }
    
    private Integer getCurrentUserId(String token) {
        if (token == null || token.isEmpty()) {
            return null;
        }
        try {
            String jwtToken = token.startsWith("Bearer ") ? token.substring(7) : token;
            Long userId = jwtUtil.getUserIdFromToken(jwtToken);
            return userId != null ? userId.intValue() : null;
        } catch (Exception e) {
            log.error("解析token失败", e);
            return null;
        }
    }
    
    private Long getCurrentUserIdLong(String token) {
        if (token == null || token.isEmpty()) {
            return null;
        }
        try {
            String jwtToken = token.startsWith("Bearer ") ? token.substring(7) : token;
            return jwtUtil.getUserIdFromToken(jwtToken);
        } catch (Exception e) {
            log.error("解析token失败", e);
            return null;
        }
    }
}

